package com.ztom.v2;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangTao
 */
public class Code32CopyListWithRandomPointer {

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList1(Node head) {
        if (head == null) {
            return null;
        }
        Map<Node, Node> mirror = new HashMap<>();

        Node cur = head;
        // 复制一份, 老的作为 key 新的作为 value
        while (cur != null) {
            mirror.put(cur, new Node(cur.val));
            cur = cur.next;
        }

        // 赋值 next 和 random
        cur = head;
        Node newCur;
        while (cur != null) {
            newCur = mirror.get(cur);
            newCur.next = mirror.get(cur.next);
            newCur.random = mirror.get(cur.random);
            cur = cur.next;
        }

        return mirror.get(head);
    }

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }

        Node cur = head;
        // 复制一份挂在后面
        while (cur != null) {
            Node next = cur.next;
            cur.next = new Node(cur.val);
            cur.next.next = next;
            cur = next;
        }

        // 赋值 random
        cur = head;
        while (cur != null) {
            Node newCur = cur.next;
            if (cur.random != null) {
                newCur.random = cur.random.next;
            }
            cur = newCur.next;
        }

        // 拆分两个链表
        Node res = head.next;
        Node pre = head;
        cur = head.next;
        while (cur.next != null) {
            pre.next = cur.next;
            cur.next = cur.next.next;
            pre = pre.next;
            cur = cur.next;
        }

        // 原链表尾结点 next 置空
        pre.next = null;
        return res;
    }
}
